<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="地址列表"
        @click-left="$router.go(-1)"
        left-arrow
      ></van-nav-bar>
    </header>
    <div class="content">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="selectAddress"
      />
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { AddressList, Toast, NavBar } from 'vant'
import { getAddressData, updateOrderAddress } from '@/api'
Vue.use(AddressList)
Vue.use(Toast)
Vue.use(NavBar)
export default {
  data () {
    return {
      chosenAddressId: '1',
      list: []
    }
  },
  mounted () {
    getAddressData({
      userid: localStorage.getItem('userid'),
      token: localStorage.getItem('token')
    }).then(res => {
      if (res.data.message === 'token验证失败') {
        Toast('您登录的用户信息已过期,请重新登录')
        localStorage.clear()
        setTimeout(() => {
          this.$router.replace('/login')
        }, 1000)
      } else {
        const arr = []
        res.data.data.map((item, index) => {
          let str = ''
          // 如果遇到直辖市，省份和城市保留一个
          if (item.province === item.city) {
            str += item.province
          } else {
            str += item.province + item.city
          }
          str += item.county
          str += item.addressDetail
          arr.push({
            id: item.addressid,
            name: item.name,
            tel: item.tel,
            address: str,
            isDefault: item.isDefault === 1
          })
        })
        this.list = arr
      }
    })
  },
  methods: {
    onAdd () {
      Toast('新增地址')
      this.$router.push('/addressadd')
    },
    onEdit (item, index) {
      Toast('编辑地址:' + index)
      this.$router.push({ path: '/updataAddress', query: { index: index } })
    },
    selectAddress (item, index) {
      const { orderid } = this.$route.query
      // console.log(index, item)
      // console.log(orderid)
      updateOrderAddress({ // 修改userinfo字段数据
        addressid: item.id,
        orderid
      }).then(res => {
        if (res.data.code === '200') {
          // this.$router.replace()
          // console.log(item)
          this.$router.go(-1)
        }
      })
    }
  }
}
</script>
